package com.thread.lesson.syn;

/**
 * @Author: Mr.Xi
 * @Description: 不安全的买票
 * @Date: Create in 10:25 2021/7/5
 * @Modified By:
 */
//不安全的买票
//线程不安全，有负数和重复数字
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        //三个人买票
        new Thread(station,"张三").start();
        new Thread(station,"李四").start();
        new Thread(station,"王五").start();
    }

}


class BuyTicket implements Runnable{
    //票
    private int ticketNum = 10;
    boolean flag = true;//外部停止方式


    @Override
    public void run() {
        //买票
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * synchronized 同步方法，锁的是this
     * @throws InterruptedException
     */
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNum <= 0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);

        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
    }
}